package com.hyts.dbutils.common;

import com.hyts.dbutils.base.TransactionManager;
import com.hyts.dbutils.bean.dbutils.DbConnectionBean;
import org.apache.commons.dbutils.QueryRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Objects;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.dbopera.dbutils.common
 * author:Libo/Alex
 * create-date:2019-06-23 21:26
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于:dbUtils工具类初始化准备处理器
 */
public interface DBUtilsPreparation extends TransactionManager {

    /**
     * 预先初始化Connection服务对象
     * @param bean
     */
    default Connection openConnection(DbConnectionBean bean){
        //判断bean是否为空
        if(Objects.isNull(bean)){
            throw new NullPointerException("传入的DbRunBean对象不可以为空!");
        }
        try {
            Class.forName(bean.getDriverClass());
            return DriverManager.getConnection(bean.getUrl(),bean.getUser(),bean.getPassword());
        } catch (ClassNotFoundException | SQLException e) {
            throw new IllegalArgumentException("获取连接失败!");
        }
    }

    /*******************************************************/

    /**
     * 预先初始化AbstractQueryRunner服务对象
     * @param bean
     */
    default DbConnectionBean build(DbConnectionBean bean){
        //判断bean是否为空
        if(Objects.isNull(bean)){
            throw new NullPointerException("传入的DbUtilsBean对象不可以为空!");
        }
        switch (bean.getExecutorType()){
            case SYNC:
                return initQueryRunner(bean);
            case ASYNC:
                return null;
            default:
                return initQueryRunner(bean);
        }
    }

    /**
     * 初始化 initQueryRunner
     * @param bean
     * @return
     */
    default DbConnectionBean initQueryRunner(DbConnectionBean bean){
        //获取queryRunner对象,判断数据源是否进行控制
        if(bean.getDataSource() == null){
            bean.setQueryRunner(new QueryRunner());
        }else{
            bean.setQueryRunner(new QueryRunner(bean.getDataSource()));
        }
        return bean;
    }
}
